import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { AppLoggerService } from '../services/logger.service';

@Injectable()
export class RequestLoggerMiddleware implements NestMiddleware {
  private readonly logger = new AppLoggerService('RequestLogger');

  use(req: Request, res: Response, next: NextFunction) {
    const { method, originalUrl, ip } = req;
    const userAgent = req.get('User-Agent') || '';
    const startTime = Date.now();

    // 记录请求开始
    this.logger.info(`Incoming Request: ${method} ${originalUrl}`, 'HTTP');
    this.logger.debug(`IP: ${ip}, User-Agent: ${userAgent}`, 'HTTP');

    // 监听响应完成
    res.on('finish', () => {
      const duration = Date.now() - startTime;
      const { statusCode } = res;
      const contentLength = res.get('Content-Length') || 0;

      // 根据状态码选择日志级别
      if (statusCode >= 500) {
        this.logger.error(`Request completed: ${method} ${originalUrl} ${statusCode} (${duration}ms)`, undefined, 'HTTP');
      } else if (statusCode >= 400) {
        this.logger.warning(`Request completed: ${method} ${originalUrl} ${statusCode} (${duration}ms)`, 'HTTP');
      } else {
        this.logger.info(`Request completed: ${method} ${originalUrl} ${statusCode} (${duration}ms)`, 'HTTP');
      }

      // 记录响应大小
      if (contentLength > 0) {
        this.logger.debug(`Response size: ${contentLength} bytes`, 'HTTP');
      }

      // 记录慢请求
      if (duration > 1000) {
        this.logger.warning(`Slow request detected: ${method} ${originalUrl} (${duration}ms)`, 'HTTP');
      }
    });

    next();
  }
}

